/* eslint-disabed */

const db = require('../mongod/db');

const accountSecret = 'accountSecret'; // 账密集合

function errMongo(res) {
  res.send({
    isok: false,
    msg: '数据库错误！请联系后端！',
  });
  return;
}

// 账密增
function addAS(req, res) {
  let query = req.body;
  query.id =
    new Date().getTime() +
    '' +
    Math.floor(Math.random() * (999999 - 10000) + 100000);
  query.creat_time = new Date().getTime();
  query.revise_time = null;

  // eslint-disable-next-line
  db.insert(accountSecret, query, (err, result) => {
    if (err) {
      errMongo(err);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '添加成功',
    };
    res.send(json);
    return;
  });
}

// 账密查
function findAS(req, res) {
  db.find(accountSecret, req.query, (err, result) => {
    if (err) {
      errMongo(err);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '查询成功',
      data: result,
    };
    res.send(json);
    return;
  });
}

// 账密删
function removeAS(req, res) {
  let query = req.query;

  // eslint-disable-next-line
  db.deleteInfo('deleteOne', accountSecret, query, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '删除成功',
    };
    res.send(json);
    return;
  });
}

function updateAS(req, res) {
  let query = req.body;
  let condition = {
    // 条件
    id: query.id,
  };
  let newValue = {
    $set: query,
  };
  newValue.revise_time = new Date().getTime();
  // 方法，集合名，条件，更新内容
  // eslint-disable-next-line
  db.update('updateOne', userinfo, condition, newValue, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '更新成功',
    };
    res.send(json);
    return;
  });
}

module.exports = {
  addAS,
  findAS,
  removeAS,
  updateAS,
};
